package com.tbl.modules.wms2.service.impl.operation;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.service.interfacelog.InterfaceLogService;
import com.tbl.modules.wms2.constant.Constant;
import com.tbl.modules.wms2.dao.operation.QualityInfoDAO;
import com.tbl.modules.wms2.dao.operation.YclInOutFlowDao;
import com.tbl.modules.wms2.dao.ordermanage.asn.AsnHeaderDAO;
import com.tbl.modules.wms2.dao.ordermanage.delivery.DeliveryDao;
import com.tbl.modules.wms2.dao.purchasein.PurchaseOrderDAO;
import com.tbl.modules.wms2.entity.operation.QualityInfoEntity;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderSaveEntity;
import com.tbl.modules.wms2.entity.report.YclInventoryUpdateDTO;
import com.tbl.modules.wms2.service.operation.QualityInfoService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import com.tbl.modules.wms2.service.report.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("yclQualityInfoService")
public class QualityInfoServiceImpl extends ServiceImpl<QualityInfoDAO, QualityInfoEntity> implements QualityInfoService {

    @Resource
    private QualityInfoDAO qualityInfoDAO;
    @Resource
    private DeliveryDao deliveryDao;
    @Resource
    private YclInOutFlowDao yclInOutFlowDao;
    @Resource
    private YclInOutFlowService yclInOutFlowService;
    @Resource
    private PurchaseOrderDAO purchaseOrderDAO;

    @Autowired
    private InterfaceLogService interfaceLogService;
    @Resource
    private WarehouseDAO warehouseDAO;

    @Resource
    private AsnHeaderDAO asnHeaderDAO;

    @Resource
    private DeliveryService deliveryService;

    @Resource(name = "yclInventoryService")
    private InventoryService inventoryService;

    @Override
    public List<QualityInfoEntity> getQualityInfoList(Map<String, Object> map) {
        return qualityInfoDAO.getQualityInfoList(map);
    }

    @Override
    public QualityInfoEntity selectQualityInfoById(String id) {
        return qualityInfoDAO.selectQualityInfoById(id);
    }

    @Override
    public Long getSequence() {
        return qualityInfoDAO.getSequence();
    }

    /**
     * 新增质检表数据
     *
     * @param
     * @return
     */
    @Override
    public QualityInfoEntity insertQcInfo(String deliveryNo, String deliveryLineNo, String materialCode, String lotsNum, String asnNumber) {
        QualityInfoEntity qualityInfoEntity = new QualityInfoEntity();
        qualityInfoEntity.setDeliveryNo(deliveryNo);
        qualityInfoEntity.setDeliveryLineNo(deliveryLineNo);
        qualityInfoEntity.setIntoInventory("0");
        qualityInfoEntity.setTobeQc("0");
        qualityInfoEntity.setMaterialCode(materialCode);
        qualityInfoEntity.setLotsNum(lotsNum);
        qualityInfoEntity.setAsnNumber(asnNumber);
        qualityInfoDAO.insert(qualityInfoEntity);
        return qualityInfoEntity;
    }


    /**
     * 发送待质检信息-存储过程调用
     *
     * @param type         待质检传Y,撤回待质检传N
     * @param qInfoId      质检信息表ycl_quality_info主键
     * @param entityId     公司ID
     * @param lotsNum      批次码
     * @param materialCode 物料编号
     * @param poNumber     采购单号
     * @param poLineNumber 采购行号
     * @param quantity     数量
     * @return
     */
    @Override
    public Map<String, Object> qcInfoToEBSProcessing(String type, String qInfoId, String entityId, String lotsNum,
                                                     String materialCode, String poNumber, String poLineNumber,
                                                     BigDecimal quantity) {
        //往map中放置请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("pType", type);
        map.put("pId", qInfoId);
        map.put("entityId", entityId);
        map.put("lotsNum", lotsNum);
        map.put("materialCode", materialCode);
        map.put("poNumber", poNumber);
        map.put("poLineNumber", poLineNumber);
        map.put("quantity", quantity);
        qualityInfoDAO.qcInfoToEBSProcessing(map);
        return map;

//        Map<String, Object> resultMap = new HashMap<>(4);
//        if (map != null && map.size() > 0) {
//            if (map.containsKey("retcode")) {
//                //存储过程调用成功
//                if (map.get("retcode").equals(Constant.SUCCESS)) {
//                    resultMap.put("result", true);
//                }
//                if (map.get("retcode").equals(Constant.ERROR)) {
//                    resultMap.put("result", false);
//                }
//                if (map.containsKey("errbuf")) {
//                    resultMap.put("msg", String.valueOf(map.get("errbuf")));
//                }
//                return resultMap;
//            }
//        }
//        resultMap.put("result", false);
//        resultMap.put("msg", "no Response");
//        return resultMap;
    }


    /**
     * 查询订单行的紧急物料信息
     * @param map
     * @return
     */
//    public EmergencyMaterialDTO getEmergencyMaterialInfo(Map<String,Object> map){
//        EmergencyMaterialDTO emDto = qualityInfoDAO.getEmergencyMaterialInfo(map);
//        return emDto;
//    }

    /**
     * 入库并更新接收表质检状态isPass
     * 查询接收表中的物料是否已上架，
     * @param deliveryNo
     * @param deliveryLineNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateQcStateForDelivery(String deliveryNo, String deliveryLineNo) {

        // 收货表
        DeliveryEntity entity = new DeliveryEntity();
        entity.setDeliveryNo(deliveryNo);
        entity.setDeliveryLineNo(deliveryLineNo);
        DeliveryEntity deliveryEntity = deliveryDao.selectOne(entity);

        String poLineId = deliveryEntity.getPoLineId();
        String deliveryId = deliveryEntity.getID();
        String lotsNum = deliveryEntity.getLotsNum();
        String materialCode = deliveryEntity.getMaterialCode();
        String asnNumber = deliveryEntity.getAsnNumber();
        String isPass = deliveryEntity.getIsPass();

        /**
         * 收货单如果已质检过，直接退出，未质检过的，先判断是否在上下架流水表，如果在直接走入库流程（先EBS入库，再Wms入库）。
         * 如果物料还未上架，直接在接收表更改isPass状态为"1"。后续当该物料上下架时，如果isPass为“1”,则需要走入库流程
         */

        if (StringUtils.isEmpty(isPass) || "0".equals(isPass)) {

            // 质检通过
            DeliveryEntity deli = new DeliveryEntity();
            deli.setID(deliveryEntity.getID());
            deli.setIsPass("1");
            deliveryDao.updateById(deli);

            // 查询物料是否已上架
            YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
            yclInOutFlowEntity.setLotsNum(lotsNum);
            yclInOutFlowEntity.setMaterialCode(materialCode);
            yclInOutFlowEntity.setBusinessCode(asnNumber);
            yclInOutFlowEntity.setInoutType("1");
            List<YclInOutFlowEntity> yclInOutFlowEntities = yclInOutFlowService.listView(yclInOutFlowEntity);

            for (YclInOutFlowEntity item : yclInOutFlowEntities) {
                this.intoInventory(item);
            }
        }
        return true;
    }


    /**
     * 入库存通用方法（先调用EBS入库存,再调用WMS入库存,入库存成功需记录日志）
     * @param yclInOutFlowEntity
     * @return
     */
    Map<String,Object> intoInventory(YclInOutFlowEntity yclInOutFlowEntity){
        Map<String,Object> resultMap = new HashMap<>();
        // 存在库存，自动入库
        if (StrUtil.isNotBlank(yclInOutFlowEntity.getLocatorCode())) {

            // 获取EBS的库位ID
            String storeCode = String.valueOf(yclInOutFlowEntity.getStoreCode());
            String areaCode = String.valueOf(yclInOutFlowEntity.getAreaCode());
            Map<String, Object> map3 = new HashMap<>();
            map3.put("code", storeCode);
            map3.put("entityId", areaCode);
            Warehouse warehouse = warehouseDAO.getWarehouseByCode(map3);
            String subCode = warehouse.getCode();
            Long locatorId = warehouse.getLocatorId();

            //获取订单行ID和接收单ID
            String materialCode = yclInOutFlowEntity.getMaterialCode();
            String asnNumber = yclInOutFlowEntity.getBusinessCode();
            String lotsNum = yclInOutFlowEntity.getLotsNum();
            Map<String,Object> map1 = new HashMap<>();
            map1.put("material_code",materialCode);
            map1.put("asn_number",asnNumber);
            map1.put("lots_num",lotsNum);
            List<DeliveryEntity> list = deliveryService.selectByMap(map1);
            DeliveryEntity deliveryEntity = list.get(0);
            String poLineId = deliveryEntity.getPoLineId();
            String deliveryId = deliveryEntity.getID();

            //先调用EBS的采购接收入库存，成功后调用WMS入库存
            PurchaseOrderSaveEntity purchaseOrderSaveEntity = new PurchaseOrderSaveEntity();
            purchaseOrderSaveEntity.setLoctorId(locatorId);
            purchaseOrderSaveEntity.setPoLineId(Long.parseLong(poLineId));
            purchaseOrderSaveEntity.setQuantity(Double.parseDouble(String.valueOf(yclInOutFlowEntity.getUpdownQuantity())));
            purchaseOrderSaveEntity.setSourceId(deliveryId);
            purchaseOrderSaveEntity.setTransDate(new Timestamp(System.currentTimeMillis()));
            purchaseOrderSaveEntity.setVendorLot(lotsNum);
            purchaseOrderSaveEntity.setSubCode(subCode);
            purchaseOrderDAO.savePurchaseOrder(purchaseOrderSaveEntity);
            String retCode = purchaseOrderSaveEntity.getRetCode();
            Long ebsLineId = purchaseOrderSaveEntity.getRcvLineId();
            if ("S".equals(retCode)) {

                // 回传 ebsLineId 到收货表
                deliveryEntity.setEbsLineId(String.valueOf(ebsLineId));
                deliveryEntity.setDeliverQuantity(yclInOutFlowEntity.getUpdownQuantity());
                deliveryEntity.setIsPass("1");
                deliveryService.edit(deliveryEntity);

                // 更新wms 库存
                YclInventoryUpdateDTO yclInventoryUpdateDTO = new YclInventoryUpdateDTO();
                yclInventoryUpdateDTO.setStoreCode(yclInOutFlowEntity.getStoreCode());
                yclInventoryUpdateDTO.setStoreName(yclInOutFlowEntity.getStoreName());
                yclInventoryUpdateDTO.setAreaCode(yclInOutFlowEntity.getAreaCode());
                yclInventoryUpdateDTO.setAreaName(yclInOutFlowEntity.getAreaName());
                yclInventoryUpdateDTO.setLocatorCode(yclInOutFlowEntity.getLocatorCode());
                yclInventoryUpdateDTO.setMaterialCode(yclInOutFlowEntity.getMaterialCode());
                yclInventoryUpdateDTO.setMaterialName(yclInOutFlowEntity.getMaterialName());
                yclInventoryUpdateDTO.setLotsNum(yclInOutFlowEntity.getLotsNum());
                yclInventoryUpdateDTO.setAmount(yclInOutFlowEntity.getUpdownQuantity());
                yclInventoryUpdateDTO.setInout("1");
                boolean b = inventoryService.updateInventory(yclInventoryUpdateDTO);
                resultMap.put("code",0);
                resultMap.put("msg",b?"EBS及WMS成功入库存":"WMS入库存失败");
                resultMap.put("result",true);
            }
            if ("E".equals(retCode)) {
                resultMap.put("code",1);
                resultMap.put("msg",purchaseOrderSaveEntity.getRetMess());
                resultMap.put("result",false);
            }
            return resultMap;
        }
        resultMap.put("code",1);
        resultMap.put("msg","库位不存在");
        resultMap.put("result",false);
        return resultMap;
    }


}
